package com.webrtc.demo.util

import android.content.Context
import android.content.SharedPreferences
import okhttp3.internal.and
import java.io.UnsupportedEncodingException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

object Utils {

    private const val SHARED_PREFERENCES_NAME = "webrtc_demo_sp"

    fun getSharedPreferences(context: Context): SharedPreferences =
        context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)

    fun md5Decode32(content: String): String? {
        val hash: ByteArray
        hash = try {
            MessageDigest.getInstance("MD5").digest(content.toByteArray(charset("UTF-8")))
        } catch (e: NoSuchAlgorithmException) {
            throw RuntimeException("NoSuchAlgorithmException", e)
        } catch (e: UnsupportedEncodingException) {
            throw RuntimeException("UnsupportedEncodingException", e)
        }
        //对生成的16字节数组进行补零操作
        val hex = StringBuilder(hash.size * 2)
        for (b in hash) {
            if (b and 0xFF < 0x10) {
                hex.append("0")
            }
            hex.append(Integer.toHexString(b and 0xFF))
        }
        return hex.toString()
    }
}